<?php
namespace File\Controller;

use Org\File\File;
use Think\Controller;

class HomeController extends Controller {

    protected static $rootPath = ROOT_PATH;
    protected static $File = ROOT_PATH;

    public function __construct() {
        parent::__construct();
        self::$File = new File();
    }

    public function index() {

        //获取本文件目录的文件夹地址
        $this->display();
    }

    public function getDir() {
        $pathName = urldecode(I('get.fileName'));
        $file     = empty($pathName) ? self::$rootPath : $pathName;
        if(isFile($file)) {
            $fileName = basename($file);
            $string   = self::$File->openFile($file);
            $ascll    = self::$File->detect_encoding($string, true); //检查编码
//            if($ascll != 'UTF-8') {
//                return $this->ajaxReturn(['status' => false, 'msg' => '暂时无法处理查看非utf8的文件']);
//            }
            return $this->ajaxReturn(['status' => true, 'msg' => ['type' => 'file', 'fileName' => $fileName, 'data' => $string]]);
        } else {
            $pathRet = self::$File->getDirs($file);
            return $this->ajaxReturn(['status' => true, 'msg' => ['type' => 'dir', 'data' => $pathRet]]);
        }
    }

    /**
     * 文件保存
     */
    public function save() {
        if(IS_POST) {
            $params = json_decode(file_get_contents('php://input'),true);
            $text = $params['text'];//内容
            $file = $params['file'];//文件
            if(!file_exists($file)) {
                return $this->ajaxReturn(['status' => false, 'msg' => '文件不存在']);
            }

            $status = self::$File->fileSave($text, $file);
            if($status) {
                return $this->ajaxReturn(['status' => true, 'msg' => '文件保存成功']);
            } else {
                return $this->ajaxReturn(['status' => false, 'msg' => '文件保存失败']);
            }
        }
    }
}